package com.ruizhong.remotehelper;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.Rect;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;


import com.ruizhong.remotehelper.util.MySurfaceHolder;
import com.ruizhong.remotehelper.util.UserEvent;
import com.ruizhong.remotehelper.util.ZoomableSurfaceView;


import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Timer;
import java.util.TimerTask;

public class ConnectingActivity extends AppCompatActivity {

    private String aimIp = "192.168.0.69";

    private EditText hiddenEditText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.connecting);

        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN
                , WindowManager.LayoutParams.FLAG_FULLSCREEN);
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            aimIp = bundle.getString("ip");
            System.out.println(aimIp);
        }
        final ZoomableSurfaceView surfaceView = (ZoomableSurfaceView) findViewById(R.id.surfaceView1);
        DisplayMetrics displayMetrics = new DisplayMetrics();
        WindowManager windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
        windowManager.getDefaultDisplay().getMetrics(displayMetrics);
        surfaceView.setParam(aimIp,displayMetrics.widthPixels,displayMetrics.heightPixels);
        SurfaceHolder holder = surfaceView.getHolder();
        holder.setKeepScreenOn(true);
        hiddenEditText =findViewById(R.id.hiddenEditText);
        hiddenEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                // 在文本变化之前执行的操作（如果需要）
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // 在文本变化时执行的操作
                // 这里只是简单地将文本设置到 TextView 上
//                textView.setText(s);
                System.out.println(s);
                UserEvent userEvent = new UserEvent(1, s.toString());
                surfaceView.ws.send(userEvent.toString());
                if (count > 0){
                    hiddenEditText.setText("");
                    hiddenEditText.setSelection(hiddenEditText.getText().length()); // 将光标移到末尾
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
                // 在文本变化之后执行的操作（如果需要）
            }
        });

        hiddenEditText.setOnKeyListener(new View.OnKeyListener(){
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                try {
                    System.out.println("监听键盘按键"+keyCode);
                    System.out.println(event.getAction());
                    UserEvent userEvent;
                    if (event.getAction() == 0){
                        userEvent = new UserEvent(2, keyCode);
                    }else{
                        userEvent = new UserEvent(3, keyCode);
                    }

                    surfaceView.ws.send(userEvent.toString());
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return true;
            }
        });
        final View activityRootView = findViewById(android.R.id.content);
        activityRootView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            private int lastVisibleViewBottom;

            @Override
            public void onGlobalLayout() {
                Rect r = new Rect();
                // 获取当前可见视图部分的矩形区域
                activityRootView.getWindowVisibleDisplayFrame(r);

                int visibleViewBottom = r.bottom;
                if (lastVisibleViewBottom != 0) {
                    // 比较上一次的可见视图底部和现在的可见视图底部
                    if (visibleViewBottom < lastVisibleViewBottom) {
                        // 可见区域变小了，可能是键盘弹出了
                    } else {
                        // 可见区域变大了，可能是键盘收起了
                        // 这里执行键盘收起后的逻辑
//                        Log.d("GlobalLayout", "Keyboard is gone");
                        hiddenEditText.setVisibility(View.INVISIBLE);
                        System.out.println("键盘被收起");
                    }
                }
                lastVisibleViewBottom = visibleViewBottom;
            }
        });
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (hasFocus) {
            final EditText hiddenEditText = findViewById(R.id.hiddenEditText);
            hiddenEditText.postDelayed(new Runnable() {
                @Override
                public void run() {
                    hiddenEditText.requestFocus();
                    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.showSoftInput(hiddenEditText, InputMethodManager.SHOW_IMPLICIT);
                }
            }, 100);
        }
    }

    public void openKeyborad(@Nullable View view) {
//        editText.setVisibility(View.VISIBLE);
//        editText.requestFocus();
        InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        inputMethodManager.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
        hiddenEditText.setVisibility(View.VISIBLE);
        hiddenEditText.requestFocus();

    }
}
